import type { ReactElement } from 'react';
import React, { useState, useEffect } from 'react';
import { Pagination, message, Collapse, Badge, Result, Tabs } from 'antd';
import styles from './index.less';
import { queryMessage, readMessage } from '@/services/user';
import { connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import { formatDateIOS } from '@/utils/utils';
import Nodata from '@/assets/noData.svg';
import moment from 'moment';

const { Panel } = Collapse;
const { TabPane } = Tabs;

const MessageList: React.FC<any> = (props): ReactElement => {
  const { messageTargetTypeEnum, targetId } = props;
  const [messageList, setMessageList] = useState<any>([]);
  const [actionId, setActionId] = useState<any>(null);
  const [messageListTotal, setMessageListTotal] = useState<any>(0);
  const [pageInfo, setPageInfo] = useState<any>({ pageNo: 1, pageSize: 20 });
  const [activeKey, setActiveKey] = useState('1');

  const getMessageList = async (info: any) => {
    const res = await queryMessage({
      type: messageTargetTypeEnum,
      targetId,
      read: activeKey == '2' ? true : activeKey == '1' ? false : null,
      ...info,
    });
    if (res && res.success) {
      setMessageList(res.data);
      setMessageListTotal(res.total);
    } else {
      message.error(res.errMsg || '');
    }
  };

  const handleChange = async (value: any) => {
    if (!value || !value.length) {
      setActionId('');
      return;
    }
    const res = await readMessage({ id: value });
    if (res && res.success) {
      setActionId(value);
      setMessageList((list) => {
        const newList = list.map((ele) => {
          if (ele.id == value) {
            ele.read = true;
          }
          return ele;
        });
        return newList;
      });
    } else {
      message.error(res.errMsg);
    }
  };

  const handlePageChange = (page: number, pageSize: number) => {
    setPageInfo({
      pageNo: page,
      pageSize: pageSize,
    });
    getMessageList({
      pageNo: page,
      pageSize: pageSize,
    });
  };

  const handleTabsChange = (key: string) => {
    setActiveKey(key);
  };

  useEffect(() => {
    getMessageList({
      pageNo: 1,
      pageSize: 20,
    });
  }, [activeKey]);

  const renderTitle = (info: any) => {
    return (
      <div className={styles.infoTop}>
        <div>
          <Badge status={info.read ? 'default' : 'error'} />
          {actionId == info.id ? (
            <span className={styles.title}>{info.title}</span>
          ) : (
            <span className={info.read ? styles.readTitle : styles.title}>{info.title}</span>
          )}
          <span className={styles.action}>
            <a href={info.url}> 前往处理</a>
          </span>
        </div>
        {info.gmtCreate && <div className={styles.time}>{moment(info.gmtCreate).format('YYYY-MM-DD HH:mm')}</div>}
      </div>
    );
  };


  return (
    <div className={styles.mainIndex}>
      <Tabs activeKey={activeKey} onChange={handleTabsChange}>
        <TabPane tab="未处理" key="1" />
        <TabPane tab="已处理" key="2" />
        <TabPane tab="全部" key="0" />
      </Tabs>
      {messageList.length ? (
        <div>
          <Collapse
            style={{ background: 'unset' }}
            bordered={false}
            expandIconPosition="end"
            onChange={handleChange}
            activeKey={actionId}
            accordion
          >
            {messageList.map((el: any) => {
              return (
                <Panel header={renderTitle(el)} key={el.id}>
                  <div className={styles.content}>
                    <p>{el.content}</p>
                    {el.userName ? (
                      <p className={styles.actionUser}>
                        <span>操作人：</span>
                        {el.userName}
                      </p>
                    ) : null}
                  </div>
                </Panel>
              );
            })}
          </Collapse>
          {messageListTotal > 20 ? (
            <Pagination
              style={{ textAlign: 'right', marginTop: '16px' }}
              current={pageInfo.pageNo}
              total={messageListTotal}
              pageSize={pageInfo.pageSize}
              onChange={handlePageChange}
            />
          ) : null}
        </div>
      ) : (
        <Result icon={<img style={{ width: '100px' }} src={Nodata} />} subTitle="暂无数据" />
      )}
    </div>
  );
};

export default connect(({ user }: ConnectState) => ({
  user,
}))(MessageList);
